import Api from './interface/api.interface'
import Axios, { AxiosInstance } from 'axios'

class ApiManager {
    readonly baseURL: string = process.env.VUE_APP_API
    private container: {[id:string]: Api}
    readonly client: AxiosInstance

    constructor() {
        this.container = {}

        // 初始化container, 扫描./module/*.ts文件并进行注册
        const context = require.context('./module', true, /\.ts$/)
        const keys = context.keys()
        keys.map(item => {
            console.log(item);
            this.registerApi(context(item).instance)
        })

        // 初始化axios
        this.client = Axios.create({ baseURL: this.baseURL })

        // 请求拦截器，根据请求调用者内置拦截器以此执行
        this.client.interceptors.request.use((config) => {
            this.container[config.headers.entity].handleInterceptor()

            return config
        })
    }

    /**
     * 将api模块注入ApiManager中
     * @param api 
     */
    registerApi(api: Api): void {
        console.log(api)
        if(this.container[api._id] == null){
            this.container[api._id] = api;
        }
    }

    /**
     * 请求发送的统一入口，传入参数为方法名称，约定以【模块名_执行动作】格式传入，如"employee_login"
     * 
     * @param name 方法名
     */
    send(name: string): void {
        let id = name.split('_')[0];
        let api = this.container[id];
        let promise:Promise<object> = api[name]();
        promise.then(
            res => {
                console.log(res)
            }
        )
        
    }
}

const instance = new ApiManager()

const client = instance.client

const baseURL = instance.baseURL

export default instance

export {client,baseURL}
